package com.learn.hibernatevalidator.chapter06.custompath;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

/**
 * @author: liyf
 * @create: 2025-01-15 22:12
 **/
public class ValidPassengerCountValidator implements ConstraintValidator<ValidPassengerCount, Car> {
    @Override
    public boolean isValid(Car car, ConstraintValidatorContext context) {
        if (car == null) {
            return true;
        }

        boolean isValid = car.getPassengers().size() <= car.getSeatCount();

        if (!isValid) {
            context.disableDefaultConstraintViolation();
            // 设置错误消息模板，和属性值
//            context.buildConstraintViolationWithTemplate("{org.hibernate.validator.referenceguide.chapter06.custompath.message}")
//                    .addPropertyNode("passengers").addConstraintViolation();

            // 使用默认的消息模板作为当前的错误消息模板。
            context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate())
                    .addPropertyNode("passengers").addConstraintViolation();
        }

        return isValid;

    }
}
